package cn.com.pc.content.jpa;

import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 站点转为 string
 */
public class TagIdsConverter implements AttributeConverter<Set<Long>, String> {

    @Override
    public String convertToDatabaseColumn(Set<Long> attribute) {
        StringJoiner stringJoiner = new StringJoiner(",");
        attribute.forEach( each -> {
            stringJoiner.add(String.valueOf(each));
        });
        return stringJoiner.toString();
    }

    @Override
    public Set<Long> convertToEntityAttribute(String dbData) {
        String[] split = dbData.split(",");
        Set<Long> result = new HashSet<Long>() {
        };
        for (String each : split) {
            if (StringUtils.hasLength(each)) {
                result.add(Long.valueOf(each));
            }
        }
        return result;
    }
}
